<template>

  <div class="cs-page-container">
    <div class="cs-filter-container">
      <el-button type="primary" size="small" icon="el-icon-edit" @click="onAdd">添加</el-button>
    </div>
    <div class="cs-filter-result">
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        size="small"
        highlight-current-row
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column
          align="center"
          label="任务id"
        >
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="任务名"
        >
          <template slot-scope="{row}">
            <span>{{ row.jobName }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="筛选器"
        >
          <template slot-scope="{row}">
            <span>{{ row.groupers | filterGrouperNames }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="显示字段"
        >
          <template slot-scope="{row}">
            <span>{{ row.displayFields | fieldsDisc }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="状态"
        >
          <template slot-scope="{row}">
            <el-button
              v-if="row.state === 2"
              type="danger"
              @click="viewFailedReason(row)"
            >
              测试/运行失败
            </el-button>
            <span v-else>{{ row.state | jobState }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="创建时间"
        >
          <template slot-scope="{row}">
            <span>{{ row.createTime | parseTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="最后成功时间"
        >
          <template slot-scope="{row}">
            <span>{{ row.lastFinishTime | parseTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          fixed="right"
          width="400"
        >
          <!-- 编辑, 删除, 测试, 上线/下线, 查看结果-->
          <template slot-scope="{ row }">

            <el-button
              v-if="row.state !== 4"
              :disabled="row.state === 1"
              type="primary"
              size="mini"
              @click="onEdit(row)"
            >
              编辑
            </el-button>

            <el-button
              :disabled="row.state === 1"
              label="测试"
              type="primary"
              size="mini"
              @click="onTest(row)"
            >
              {{ row.state &lt; 3 ? '测试' : '手动执行' }}
            </el-button>
            <el-button
              v-if="row.state===3"
              :disabled="row.state === 1"
              label="上线"
              type="primary"
              size="mini"
              @click="setOnline(row,1)"
            >
              上线
            </el-button>

            <el-button
              v-if="row.state===4"
              :disabled="row.state === 1"
              label="下线"
              type="danger"
              size="mini"
              @click="setOnline(row, 0)"
            >
              下线
            </el-button>
            <el-button
              label="查看"
              type="primary"
              size="mini"
              @click="onView(row)"
            >
              查看结果
            </el-button>

            <el-button
              v-if="row.state < 4"
              :disabled="row.state === 1"
              label="删除"
              type="danger"
              size="mini"
              @click="onDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <JobEditor
      :visible.sync="editVisible"
      :value="tempJob"
      @success="addOrUpdateJob"
    ></JobEditor>

    <el-dialog
      :visible.sync="oneShotTimeRangeVisible"
      :title="oneShotJob.title"
      @close="oneShotTimeRangeVisible = false"
    >
      <span>请选择执行任务的日期: </span>
      <el-date-picker
        v-model="oneShotJob.daterangeValue"
        :picker-options="daterangePickerOptions"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="创建起始时间"
        end-placeholder="创建结束时间"
        value-format="yyyy/MM/dd"
      />
      <span slot="footer">
        <el-button @click="oneShotTimeRangeVisible=false">取消</el-button>
        <el-button :disabled="!oneShotJob.daterangeValue" type="primary" @click="executeOneShotJob">确定</el-button>
      </span>
    </el-dialog>
    <auto-page @buildInDialog="handleBuildInPage" pageId="800060"></auto-page>

  </div>
</template>

<script>
import {
  addJob,
  preUpdateJob,
  updateJob,
  deleteJob,
  jobList,
  runJobOnce,
  setJobOnline,
  setJobOffline
} from '@/api/bx';
import BxMixin from './mixin';
import JobEditor from './components/jobEditor';
import AutoPage from '@views/auto-page'

export default {
  name: 'JobList',
  components: { JobEditor, AutoPage },
  filters: {
    fieldsDisc(fields) {
      if (!fields) {
        return ''
      }
      const result = []
      fields.forEach(field => {
        result.push(field.desc || field.fieldName)
      })
      return result.join(',')
    },
    jobState(state) {
      const stateEnum = {
        0: '编辑完成',
        1: '手动执行中...',
        2: '测试失败',
        3: '测试成功',
        4: '在线',
        5: '在线运行失败'
      }
      return stateEnum[state]
    }

  },
  mixins: [BxMixin],

  data() {
    return {
      listLoading: true,
      list: [],
      editVisible: false,
      tempJob: {},
      oneShotTimeRangeVisible: false,
      oneShotJob: {}
    }
  },
  created() {
    this.doSearch()
  },
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    handleBuildInPage(operation, row) {
      console.log('fucker. me .', operation, row)
    },
    doSearch() {
      jobList().then(resp => {
        console.log('do search...')
        this.list = resp.data.list
        this.listLoading = false
        let hasRunning = false
        this.list.forEach(item => {
          if (item.state === 1) {
            hasRunning = true
          }
        })
        if (hasRunning) {
          this.autoRefresh()
        } else {
          clearInterval(this.timer)
          this.timer = null
        }
      })
    },
    onAdd() {
      // 编辑页面
      this.tempJob = {
        jobName: '',
        groupers: [],
        displayFields: [],
        timer: null
      }
      this.editVisible = true
    },
    addOrUpdateJob(job) {
      this.editVisible = false
      if (job.id) {
        preUpdateJob(job).then(resp => {
          if (resp.data.msg) {
            this.$confirm(resp.data.msg + ', 是否修改?').then(() => {
              updateJob(job).then(resp => {
                this.doSearch()
              })
            })
          } else {
            updateJob(job).then(resp => {
              this.doSearch()
            })
          }
        })
        updateJob(job).then(resp => {
          this.doSearch()
        })
      } else {
        addJob(job).then(resp => {
          this.doSearch()
        })
      }
    },

    onEdit(row) {
      // 编辑页面
      this.tempJob = Object.assign({}, row)
      this.editVisible = true
    },
    onView(row) {
      // 查看数据
      this.$router.push('/bx/result-list?id=' + row.id)
    },
    onTest(row) {
      this.oneShotJob = {
        id: row.id,
        title: '选择执行\'' + row.jobName + '\'的时间范围',
        daterangeValue: null
      }
      this.oneShotTimeRangeVisible = true
    },
    onDelete(row) {
      deleteJob(row.id).then(resp => {
        this.doSearch()
      })
    },
    setOnline(row, online) {
      if (online) {
        setJobOnline(row.id).then(resp => {
          this.doSearch()
        })
      } else {
        setJobOffline(row.id).then(resp => {
          this.doSearch()
        })
      }
    },
    executeOneShotJob() {
      this.oneShotTimeRangeVisible = false
      if (!this.oneShotJob.id) {
        return
      }
      runJobOnce({
        id: this.oneShotJob.id,
        startTime: this.oneShotJob.daterangeValue[0],
        endTime: this.oneShotJob.daterangeValue[1]
      }).then(resp => {
        this.autoRefresh()
      })
    },
    autoRefresh() {
      if (!this.timer) {
        const self = this
        this.timer = setInterval(() => {
          self.doSearch()
        }, 3000)
      }
    },
    viewFailedReason(row) {
      console.log(row.lastFailedReason)
      this.$alert(row.lastFailedReason, '错误信息')
    }
  }

}
</script>

<style scoped>

</style>
